package com.pty.demo.behaviour.interpreter;

import java.util.Stack;

/**
 * @author pengty
 * @date 2020/3/16
 */
public class CalculatorContext {

    private Stack<Expression> expressionStack = new Stack<>();

    public CalculatorContext(String expression) {
        this.analyse(expression);
    }

    private void analyse(String expression) {
        String[] elements = expression.split(" ");
        Expression leftExpr, rightExpr;
        for (int i = 0, len = elements.length; i < len; ++i) {
            switch (elements[i]) {
                case "+":
                    leftExpr = this.expressionStack.pop();
                    rightExpr = new VarTerminalExpression(Integer.parseInt(elements[++i]));
                    this.expressionStack.push(new AddOperationExpression(leftExpr, rightExpr));
                    break;
                case "-":
                    leftExpr = this.expressionStack.pop();
                    rightExpr = new VarTerminalExpression(Integer.parseInt(elements[++i]));
                    this.expressionStack.push(new SubOperationExpression(leftExpr, rightExpr));
                    break;
                default:
                    this.expressionStack.push(new VarTerminalExpression(Integer.parseInt(elements[i])));
                    break;
            }
        }
    }

    public int calculate() {
        return this.expressionStack.pop().interpreter();
    }
}
